﻿using UnityEngine;

// 确保Collider2D被挂到单体上
[RequireComponent(typeof(Collider2D))]
public class FlockItem : MonoBehaviour
{
    // 碰撞器
    Collider2D collider;
    public Collider2D Collider { get { return collider; } }

    // 单体质量
    public float mass = 1.0f;

    // >>>>>自身移动、旋转相关<<<<<
    // 移动速度
    Vector2 velocity;
    public Vector2 Velocity { get { return velocity; } }

    // 移动速度上限
    [SerializeField]
    float maxSpeed;
    public float MaxSpeed { get { return maxSpeed; } }
    float sqrMaxSpeed;

    // 加速度
    Vector2 acceleration;

    // 旋转阻尼
    [Range(0, 10)]
    public float rotateSpeed;

    // >>>>>集群相关参数<<<<<
    // 判断相邻单体的半径
    [SerializeField]
    float neighborRadius;
    public float NeighborRadius { get { return neighborRadius; } }

    // 判断散开的半径
    [SerializeField]
    float seperateRadius;
    public float SeperateRadius { get { return seperateRadius; } }

    // 散开因子，用于放大远离其他单体的向量
    [SerializeField]
    float seperateForceMultiplier;
    public float SeperateForceMultiplier { get { return seperateForceMultiplier; } }

    // 最大受力
    [SerializeField]
    float maxForce;

    // 受力因子，用于控制力的大小（力的灵敏度）
    [SerializeField]
    float forceFactor;

    void Start()
    {
        sqrMaxSpeed = maxSpeed * maxSpeed;
        collider = GetComponent<Collider2D>();
    }

    void FixedUpdate()
    {
        float dt = Time.fixedDeltaTime;

        // >>>>>更新速度<<<<<
        velocity += acceleration * dt;

        // 限制最大速度
        if (velocity.sqrMagnitude > sqrMaxSpeed)
        {
            velocity = velocity.normalized * maxSpeed;
        }

        // >>>>>更新位移<<<<<
        Vector3 move = velocity * dt;
        transform.position += move;

        // >>>>>更新朝向<<<<<
        if (velocity.sqrMagnitude > 0.00001)
        {
            // 使用线性插值计算当前帧的朝向
            Vector3 up = Vector3.Slerp(transform.up, velocity, rotateSpeed * dt);
            transform.up = up;
        }
    }

    public void AddFlockForce(Vector2 force)
    {
        force *= forceFactor;
        acceleration = Vector2.ClampMagnitude(force, maxForce) / mass;
    }
}
